from django.db.models import F
from django.shortcuts import render

# Create your views here.
from rest_framework.decorators import action
from rest_framework.mixins import ListModelMixin
from rest_framework.permissions import IsAuthenticated
from rest_framework.response import Response
from rest_framework.status import HTTP_404_NOT_FOUND
from rest_framework.viewsets import GenericViewSet, ModelViewSet

from community.models import *
from community.serializers import *
from utils.Pageination_util import ArticlePagination


class LabelViewSet(GenericViewSet, ListModelMixin):
    queryset = Label.objects.all()
    serializer_class = LabelSerializer
    permission_classes = [IsAuthenticated]


class ArticleViewSet(ModelViewSet):
    queryset = Article.objects.filter(is_delete=False)
    serializer_class = ArticleSerializer
    permission_classes = [IsAuthenticated]
    # 分页器类
    pagination_class = ArticlePagination

    def get_queryset(self):
        if self.action in ["list", "retrieve"]:
            return self.queryset.filter(status=1)
        else:
            return self.queryset

    def get_serializer_class(self):
        if self.action in ["comment"]:
            return CommentSerializer
        else:
            return self.serializer_class

    def create(self, request, *args, **kwargs):
        request.POST._mutable = True
        request.data["user"] = request.user.id
        return ModelViewSet.create(self, request, *args, **kwargs)

    def retrieve(self, request, *args, **kwargs):
        # self.queryset()得到文章的查询集对象
        # filter(id=kwargs['pk']) 通过id得到指定的文章
        # update修改 page_view浏览量
        # F通过F得到当前文章的浏览量的值 在原有的基础上+1
        self.get_queryset().filter(id=kwargs['pk']).update(page_view=F('page_view') + 1)
        return ModelViewSet.retrieve(self, request, *args, **kwargs)

    @action(methods=["get"], detail=True)
    def comment(self, request, pk):
        """
        得到指定id文章的评论
        :param request:
        :param pk: 文章id
        :return:  返回序列化之后的数据
        """
        try:
            article = self.get_queryset().get(id=pk)
        except Article.DoesNotExist:
            return Response(status=HTTP_404_NOT_FOUND)
        # 得到该文章下面的一级评论 父级评论为空的评论
        comments = article.comment_set.filter(parent_comment__isnull=True)
        comments_page = self.paginate_queryset(comments)
        serializer = self.get_serializer(comments_page, many=True)
        return self.get_paginated_response(serializer.data)


class CommentViewSet(ModelViewSet):
    # 第一个只能查看展示文章的评论 只能对发布的文章进行评论
    # 文章没有被逻辑删除的
    queryset = Comment.objects.filter(article__status=1, article__is_delete=False, is_delete=False)
    serializer_class = CommentSerializer
    permission_classes = [IsAuthenticated]
    pagination_class = ArticlePagination

    def get_serializer_class(self):
        if self.action in ['retrieve']:
            return SonCommentSerializer
        else:
            return self.serializer_class

    def create(self, request, *args, **kwargs):
        request.POST._mutable = True
        request.data["user"] = request.user.id
        return ModelViewSet.create(self, request, *args, **kwargs)

    def retrieve(self, request, *args, **kwargs):
        """
        得到当前评论下的子级评论
        :param request:
        :param args:
        :param kwargs:
        :return:
        """
        try:
            comment = self.get_queryset().get(id=kwargs['pk'])
        except Comment.DoesNotExist:
            return Response(status=HTTP_404_NOT_FOUND)
        comments_page=self.paginate_queryset(comment.parent_comment_set.all())
        serializer = self.get_serializer(comments_page, many=True)
        return self.get_paginated_response(serializer.data)
